// vncpassword.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"

#include <string>

#include "VNC_password.h"

bool IsPasswordValueDiffrence(HKEY hKey, PBYTE pass, int passLength);

const LPWSTR szRegKeyVNC    = TEXT("Software\\RealVNC\\WinVNC4");
const LPWSTR szRegValVNCPWD = TEXT("password");


extern "C" __declspec( dllexport ) int SetVNCPassword(char *pass)
{
	int resVal = 0;
	if (pass==NULL || pass[0]==0)
	{
	}
	else
	{
		std::string strPass(pass);
		char *strBuff = new char[strPass.length() + 1];
		memset(strBuff, 0, strPass.length() + 1);
		memcpy(strBuff, strPass.c_str(), strPass.length());

		rfb::PlainPasswd password(strBuff);
		rfb::ObfuscatedPasswd obfPwd(password);
	
		DWORD dw;
		HKEY hKey = NULL;

      //  if (::RegCreateKeyEx(
      //                  HKEY_CURRENT_USER, 
      //                  szRegKeyVNC, 0,
		    //            REG_NONE,
		    //            REG_OPTION_NON_VOLATILE,
						//KEY_WRITE|KEY_READ,
      //                  NULL, 
      //                  &hKey, 
      //                  &dw)==ERROR_SUCCESS)
		if ( ::RegOpenKeyEx( HKEY_CURRENT_USER , szRegKeyVNC, NULL, KEY_WRITE|KEY_READ, &hKey) == ERROR_SUCCESS )	
		{
			if (IsPasswordValueDiffrence(hKey, (PBYTE)obfPwd.buf, obfPwd.length))
			{
				::RegSetValueEx(hKey, szRegValVNCPWD, NULL, REG_BINARY, (PBYTE)obfPwd.buf, obfPwd.length);
				resVal = 1;
			}

			::RegCloseKey(hKey);
		}
	}

	return resVal;
}	

bool IsPasswordValueDiffrence(HKEY hKey, PBYTE pass, int passLength)
{
	DWORD dwOldPass[5000];
    DWORD dwBufSize = sizeof(dwOldPass);
	DWORD lpType;
	bool bRes = true;

	if (::RegQueryValueEx(hKey, szRegValVNCPWD, NULL, &lpType, (PBYTE)dwOldPass, &dwBufSize)==ERROR_SUCCESS)
	{
		if ( memcmp(dwOldPass, pass, passLength)==0 ) 
		{
			bRes = false;
		}
	}

	return bRes;
}